
#include "pngcompress_jni.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "pngcompress.h"

/*
 * Class:     org_x_util_PNGCompress
 * Method:    nativeCompress
 * Signature: (Ljava/lang/String;IZFZ)I
 * Signature: ([BILjava/lang/String;IZFZ)I
 */
JNIEXPORT jbyteArray JNICALL Java_org_x_util_PNGCompress_nativeCompress
  (JNIEnv *jenv, jobject obj, jbyteArray src_buf, jstring jquality, jint speed, jboolean ordered, jfloat floyd, jboolean verbose)
{
    int retval = 0;
    jclass thiz = (*jenv)->GetObjectClass(jenv, obj);

    const char *quality = (*jenv)->GetStringUTFChars(jenv, jquality, 0);

    bool isCopy = false;
    char *input_buf = (char*)(*jenv)->GetByteArrayElements(jenv, src_buf, &isCopy);

    char *output_buf = NULL;
    size_t out_length = 0;
    retval = png_compress(input_buf, &output_buf, &out_length, quality, speed, ordered, floyd, verbose);

    if (retval != 0 || output_buf == NULL || out_length < 0)
        out_length = 0;

    (*jenv)->ReleaseByteArrayElements(jenv, src_buf, input_buf, 0);

    jfieldID id = (*jenv)->GetFieldID(jenv, thiz, "dstSize", "I");
    (*jenv)->SetLongField(jenv, obj, id, out_length);

    id = (*jenv)->GetFieldID(jenv, thiz, "retValue", "I");
    (*jenv)->SetLongField(jenv, obj, id, retval);

    jbyteArray outbytes = (*jenv)->NewByteArray(jenv, (jsize)out_length);

    if (outbytes != 0) {
        if (retval == 0 && output_buf != NULL && out_length > 0)
            (*jenv)->SetByteArrayRegion(jenv, outbytes , 0, (jsize)out_length, (jbyte*)output_buf);
    }

    if (output_buf != NULL)
        free(output_buf);

    return 0;
}


